<template>
  <div v-if="data._isInit" class="l-rblock">
    <l-data-list
      :columns="config.columns"
      :isMore="!!config.moduleId"
      :label="config.title"
      :data="dataSource"
      @more="handleMore"
      @itemClick="handleClick"
    ></l-data-list>

    <template v-if="isLoad">
      <l-dialog
        v-if="isDialog"
        :title="$t(formTitle)"
        :visible.sync="formVisible"
        :height="dialogHeight"
        :width="dialogWidth"
        :hasBtns="false"
        @closed="handleCloseForm"
        @opened="handleOpenedForm"
      >
        <l-form-viewer
          ref="form"
          :formInfo="formInfo"
          :isAuth="true"
          :isRead="true"
        ></l-form-viewer>
      </l-dialog>
      <l-drawer
        v-else
        :title="$t(formTitle)"
        :visible.sync="formVisible"
        :width="drawerWidth"
        :showOk="false"
        :showClose="false"
        @closed="handleCloseForm"
        @opened="handleOpenedForm"
      >
        <l-form-viewer
          ref="form"
          :formInfo="formInfo"
          :isAuth="true"
          :isRead="true"
        ></l-form-viewer>
      </l-drawer>
    </template>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import viewMixins from "../mixins/view";
const apiScheme = window.$api.custmerForm.scheme;

export default {
  props: ["data", "isPreview"],
  mixins: [viewMixins()],
  data() {
    return {
      isLoad: false,
      formSchemeId: "",
      formScheme: null,
      formTitle: "",
      formVisible: false,
      formEditRow: null,

      // 主表数据
      mainTable: null,
      mainTableIndex: 0,
    };
  },
  asyncComputed: {
    dataSource: {
      async get() {
        const { orderId, formVerison, form, limitRow, maxRows, moduleId } =
          this.config;
        if (orderId && formVerison && form) {
          const queryData = {
            paginationInputDto: {
              rows: limitRow == 1 ? maxRows : 100000,
              page: 1,
              sidx: orderId,
            },
          };
          const res =
            (await this.$awaitWraper(
              apiScheme.getDataPage(moduleId, formVerison, queryData)
            )) || {};
          return res.rows || [];
        } else {
          return [];
        }
      },
    },
  },
  computed: {
    ...mapGetters(["modules"]),
    formInfo() {
      return this.formScheme.formInfo;
    },
    isDialog() {
      return this.formInfo.openType != "2";
    },
    dialogHeight() {
      return this.formInfo.dialogHeight || 600;
    },
    dialogWidth() {
      return this.formInfo.dialogWidth || 800;
    },
    drawerWidth() {
      return this.formInfo.drawerWidth || 600;
    },
  },
  methods: {
    handleMore() {
      const { moduleId } = this.config;
      if (!this.isPreview && moduleId) {
        const module = this.modules.find((t) => t.f_ModuleId == moduleId);
        if (module) {
          this.$router.$lrRouter.goto(module);
        }
      }
    },
    async handleClick(row) {
      const loading = this.$loading({
        lock: true,
        text: this.$t("加载表单中..."),
        spinner: "el-icon-loading",
      });

      await this.initForm();
      loading.close();

      this.formEditRow = row;
      this.showForm("查看详情");
    },
    async initForm() {
      const { formVerison } = this.config;
      if (!this.isLoad) {
        const { f_Scheme, f_Id } =
          (await this.$awaitWraper(apiScheme.getHistory(formVerison))) || {};
        this.formScheme = JSON.parse(f_Scheme);
        this.formSchemeId = f_Id;

        // 主表
        this.mainTableIndex = this.formScheme.db.findIndex(
          (t) => t.type == "main"
        );
        this.mainTable = this.formScheme.db[this.mainTableIndex];
        this.isLoad = true;
      }
    },
    handleCloseForm() {
      this.$refs.form.resetFormData();
    },
    handleOpenedForm(showLoading, hideLoading) {
      showLoading("加载数据中");
      this.$nextTick(async () => {
        if (this.formScheme.formType == 1) {
          let formdata = {};
          formdata[this.mainTable.name] = [this.formEditRow];
          const mainDataQuery = {};
          if (this.formScheme.db.length > 0) {
            this.formScheme.db.forEach((db) => {
              mainDataQuery[db.relationField] =
                this.formEditRow[db.relationField];
            });
            const res = await this.$awaitWraper(
              apiScheme.getViewData(this.formSchemeId, {
                mainData: JSON.stringify(mainDataQuery),
              })
            );
            formdata = {
              ...formdata,
              ...res,
            };
          }
          this.$refs.form.init(formdata);
        } else {
          const mainTablePk = this.formScheme.primaryKey;
          const data = await this.$awaitWraper(
            apiScheme.getData(this.formSchemeId, {
              key: mainTablePk,
              keyValue: this.formEditRow[`${mainTablePk.toLowerCase()}0`],
            })
          );
          this.$refs.form.init(data);
        }
        hideLoading();
      });
    },
    showForm(text) {
      this.formTitle = text;
      this.formVisible = true;
    },
  },
};
</script>

